//
//  WBN_FM_MyCachePlayerViewController.m
//  GoodManNews
//
//  Created by 王博男 on 16/1/14.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "WBN_FM_MyCachePlayerViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface WBN_FM_MyCachePlayerViewController () <AVAudioPlayerDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) AVAudioPlayer *player;
@property (nonatomic, retain) UISlider *slider;
@property (nonatomic, retain) NSTimer *timer;

@property (nonatomic, retain) UILabel *leftTimeL;
@property (nonatomic, retain) UILabel *rightTimeL;
@property (nonatomic, retain) UIButton *leftB;
@property (nonatomic, retain) UIButton *rightB;
@property (nonatomic, retain) UIButton *playB;

@property (nonatomic, retain) UITableView *tableV;
@property (nonatomic, retain) UIScrollView *scrollV;
@property (nonatomic, retain) UILabel *titleL;

@property (nonatomic, retain) NSTimer *titleTimer;
// 记录滚动方向
@property (nonatomic, assign) BOOL tempBol;
// 记录是不是第一次进来
@property (nonatomic, assign) BOOL countBool;
// 上一次是第几首
@property (nonatomic, assign) NSInteger lastNum;

@end

@implementation WBN_FM_MyCachePlayerViewController

//+(instancetype)sharePlayerViewController
//{
//    static WBN_FM_MyCachePlayerViewController *playerVC = nil;
//    if (nil == playerVC) {
//        playerVC = [[WBN_FM_MyCachePlayerViewController alloc] init];
//    }
//    return playerVC;
//}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = YES;
    
    if (NO == self.countBool) {
        
        self.countBool = YES;
        
    } else {
        
        if (self.lastNum != self.count) {
            
            [self.player stop];
            [self.timer invalidate];
            
            self.lastNum = self.count;
            
            [self.titleL removeFromSuperview];
            
            [self createPlayer];
            
        }
        
    }
    
    self.lastNum = self.count;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self createView];
    [self createTableV];
    
    [self createPlayer];
    
}

- (void)createView
{
    UIImageView *imageV = [UIImageView new];
    imageV.image = [UIImage imageNamed:@"xingkong"];
    [self.view addSubview:imageV];
    
    [imageV mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.edges.equalTo(self.view);
        
    }];
    
    
    UIVisualEffectView *effectV = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    [self.view addSubview:effectV];
    
    [effectV mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.edges.equalTo(self.view);
        
    }];
    
    
    self.slider = [UISlider new];
    [self.slider setThumbImage:[UIImage imageNamed:@"anniu"] forState:UIControlStateNormal];
    [self.slider addTarget:self action:@selector(sliderAction) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.slider];
    
    [self.slider mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.equalTo(@200);
        make.left.equalTo(@90);
        make.height.equalTo(@30);
        make.right.equalTo(self.view).offset(-90);
        
    }];
    
    
    self.leftTimeL = [UILabel new];
    [self.view addSubview:self.leftTimeL];
    
    [self.leftTimeL mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.equalTo(self.slider);
        make.left.equalTo(@10);
        make.right.equalTo(@70);
        make.height.equalTo(self.slider);
        
    }];
    
    
    self.rightTimeL = [UILabel new];
    [self.view addSubview:self.rightTimeL];
    
    [self.rightTimeL mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.slider);
        make.left.equalTo(self.slider.mas_right).with.offset(10);
        make.right.equalTo(self.view).offset(-10);
        make.height.equalTo(self.slider);
        
    }];
    
    
    self.leftB = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.leftB setImage:[UIImage imageNamed:@"fm_before_night@3x"] forState:UIControlStateNormal];
    [self.leftB addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.leftB];
    
    [self.leftB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.slider.mas_bottom).offset(50);
        make.left.equalTo(self.view).offset(80);
        make.height.equalTo(@30);
        make.width.equalTo(@30);
        
    }];
    
    
    self.rightB = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.rightB setImage:[UIImage imageNamed:@"fm_next_night@3x"] forState:UIControlStateNormal];
    [self.rightB addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.rightB];
    
    [self.rightB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.leftB);
        make.right.equalTo(self.view).offset(-80);
        make.height.equalTo(@30);
        make.width.equalTo(@30);
        
    }];
    
    
    self.playB = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.playB setImage:[UIImage imageNamed:@"fm_play_night@3x"] forState:UIControlStateNormal];
    [self.playB setImage:[UIImage imageNamed:@"fm_pause_night@3x"] forState:UIControlStateSelected];
    [self.playB addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.playB];
    
    [self.playB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.slider.mas_bottom).offset(45);
        make.height.equalTo(@40);
        make.width.equalTo(@40);
        
    }];
    
    
    self.scrollV = [UIScrollView new];
    [self.view addSubview:self.scrollV];
    
    [self.scrollV mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view).offset(80);
        make.centerX.equalTo(self.view);
        make.width.equalTo(@150);
        make.height.equalTo(@50);
        
    }];
    
}

- (void)createTitleLabel
{
    self.titleL = [UILabel new];
    self.titleL.text = [self.nameArr objectAtIndex:self.count];
    [self.scrollV addSubview:self.titleL];
    
    [self.titleL mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.equalTo(self.scrollV);
        make.left.equalTo(self.scrollV);
        make.height.equalTo(self.scrollV);
        
    }];
    
    [self createTitleTimer];
}

- (void)getWidth
{
    CGRect frame = [self.titleL.text boundingRectWithSize:CGSizeMake(1000, 35) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:16.0] forKey:NSFontAttributeName] context:nil];
    
    
    [self.titleL mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.width.equalTo(@(frame.size.width));
        
        if (frame.size.width <= self.scrollV.frame.size.width) {
            
            make.centerX.equalTo(self.scrollV);
            
        }
        
    }];
    
}

- (void)createTitleTimer
{
    self.titleTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
}

- (void)createTableV
{
    self.tableV = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableV.backgroundColor = [UIColor clearColor];
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    [self.view addSubview:self.tableV];
    
    [self.tableV mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.equalTo(self.playB.mas_bottom).with.offset(30);
        make.left.equalTo(self.view).offset(30);
        make.right.equalTo(self.view).offset(-30);
        make.bottom.equalTo(self.view);
        
    }];
}

- (void)createPlayer
{
    [self createTitleLabel];
    
    self.leftTimeL.text = @"00:00";
    self.rightTimeL.text = @"00:00";
    
    self.playB.selected = YES;
    
    NSURL *url = [NSURL fileURLWithPath:[self.arr objectAtIndex:self.count]];
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    self.player.delegate = self;
    [self.player play];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
}

- (void)timerAction:(NSTimer *)sender
{
    if (sender == self.timer) {
        
        self.leftTimeL.text = [NSString stringWithFormat:@"%02ld:%02ld", (NSInteger)self.player.currentTime / 60, (NSInteger)self.player.currentTime % 60];
        self.rightTimeL.text = [NSString stringWithFormat:@"%02ld:%02ld", (NSInteger)self.player.duration / 60, (NSInteger)self.player.duration % 60];
        
        self.slider.maximumValue = self.player.duration;
        self.slider.value = self.player.currentTime;
        
    } else {
        
        if (NO == self.tempBol) {
            
            if (self.titleL.frame.origin.x + self.titleL.bounds.size.width >= self.scrollV.bounds.origin.x + self.scrollV.bounds.size.width) {
                
                self.titleL.frame = CGRectMake(self.titleL.frame.origin.x - 1, self.titleL.frame.origin.y, self.titleL.frame.size.width, self.titleL.frame.size.height);
                
            } else {
                
                self.titleL.frame = CGRectMake(self.titleL.frame.origin.x + 1, self.titleL.frame.origin.y, self.titleL.frame.size.width, self.titleL.frame.size.height);
                
                self.tempBol = YES;
                
            }
            
        } else {
            
            if (self.titleL.frame.origin.x <= self.scrollV.bounds.origin.x) {
                
                self.titleL.frame = CGRectMake(self.titleL.frame.origin.x + 1, self.titleL.frame.origin.y, self.titleL.frame.size.width, self.titleL.frame.size.height);
                
                
            } else {
                
                self.titleL.frame = CGRectMake(self.titleL.frame.origin.x - 1, self.titleL.frame.origin.y, self.titleL.frame.size.width, self.titleL.frame.size.height);
                
                self.tempBol = NO;
                
            }
            
        }
        
    }
}

- (void)sliderAction
{
    self.player.currentTime = self.slider.value;
}

- (void)buttonAction:(UIButton *)sender
{
    if (sender == self.playB) {
        
        if (sender == self.playB) {
            
            if (YES == self.player.playing) {
                
                [self.player pause];
                self.playB.selected = NO;
                
            } else if (NO == self.player.playing) {
                
                [self.player play];
                self.playB.selected = YES;
                
            }
            
        }
        
    } else if (sender == self.rightB) {

        if (self.count == self.arr.count - 1) {
            
            NSLog(@"当前是最后一个节目");
            
        } else {
            
            [self.player stop];
            [self.timer invalidate];
            [self.titleL removeFromSuperview];
            
            self.count++;
            
            [self createPlayer];
            
        }
        
    } else {
        
        if (0 == self.count) {
            
            NSLog(@"当前是第一个节目");
            
        } else {
            
            [self.player stop];
            [self.timer invalidate];
            [self.titleL removeFromSuperview];
            
            self.count--;
            
            [self createPlayer];
            
        }
        
    }
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [self.timer invalidate];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellStr = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
    if (!cell) {
        cell = [UITableViewCell new];
    }
    
    cell.textLabel.text = [self.nameArr objectAtIndex:indexPath.row];
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    cell.textLabel.textColor = [UIColor colorWithWhite:0.278 alpha:1.000];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.count != indexPath.row) {
        
        [self.player stop];
        [self.timer invalidate];
        
        self.count = indexPath.row;
        
        [self.titleL removeFromSuperview];
        
        [self createPlayer];
        
        self.titleL.text = self.nameArr[self.count];

        [self getWidth];
    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [self.player stop];
    [self.timer invalidate];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
